package com.application.metroscanner.fragments;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.application.metroscanner.adapters.ClustersListAdapter;
import com.application.metroscanner.tools.Classifier;
import com.application.metroscanner.tools.FileManager;
import com.example.metroscanner.R;

public class RideGroupListFragment extends Fragment {

	private OnItemSelectedListener listener;
	ListView groupList;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_groups_list, container,
				false);

		displayGroups(view);

		return view;
	}

	public interface OnItemSelectedListener {
		public void onRideGroupeSelected(Classifier.Cluster iCluster);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity instanceof OnItemSelectedListener) {
			listener = (OnItemSelectedListener) activity;
		} else {
			throw new ClassCastException(activity.toString()
					+ " must implemenet MyListFragment.OnItemSelectedListener");
		}
	}

	@Override
	public void onDetach() {
		super.onDetach();
		listener = null;
	}

	/**
	 * Display ride groups
	 */
	private void displayGroups(View view) {
		ListView groupList = (ListView) view.findViewById(R.id.groupList);

		FileManager fileManager = FileManager.getInstance(getActivity());
		ArrayList<String> rideList = fileManager
				.ReadFile(getString(R.string.CSV_rides));

		ArrayList<Classifier.Cluster> clusters = Classifier.classify(rideList);

		// Create ArrayAdapter
		ClustersListAdapter listAdapter = new ClustersListAdapter(
				getActivity(), clusters);
		groupList.setAdapter(listAdapter);

		groupList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				//send the item selected
				listener.onRideGroupeSelected((Classifier.Cluster) parent
								.getItemAtPosition(position));
			}
		});

	}

}
